import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Student} from './student';
import {Observable} from 'rxjs';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

@Injectable({
  providedIn: 'root'
})
export class StudentService {
  private uri = '/api/student/';

  constructor(
    private http: HttpClient,
  ) {
  }

  save(student: Student) {
    this.http.post<Student>(`${this.uri}save`, student, httpOptions).pipe().subscribe(stu => student.id = stu.id);
  }

  list(): Observable<Student[]> {
    return this.http.get<Student[]>(`${this.uri}list`);
  }

  delete(id: number) {
    return this.http.get(`${this.uri}delete/${id}`);
  }

  update(student: Student) {
    return this.http.post<Student>(`${this.uri}update`, student, httpOptions).pipe().subscribe(stu => student.id = stu.id);
  }

  get(id: number): Observable<Student> {
    return this.http.get<Student>(`${this.uri}list/${id}`);
  }
}
